package model;

import java.util.ArrayList;
import java.util.List;

/**
 * 单个滑块
 */
public class Block {
    /**
     * 滑块的编号
     */
    private char code;

    /**
     * 滑块包含的网格
     */
    private List<Cell> cells;

    /**
     * 滑块构造方法
     *
     * @param cell 赋予此滑块的初始网格
     */
    public Block(Cell cell) {
        this.code = cell.getCode();
        this.cells = new ArrayList<>();
        this.cells.add(cell);
    }

    /**
     * 获取滑块的下标范围
     *
     * @return 此滑块的范围数组，依次是[xMin,yMin,xMax,yMax]
     */
    public int[] getRange() {
        int xMin = Integer.MAX_VALUE, yMin = Integer.MAX_VALUE, xMax = Integer.MIN_VALUE, yMax = Integer.MIN_VALUE;
        for (Cell cell : this.cells) {
            xMin = Integer.min(xMin, cell.getCol());
            xMax = Integer.max(xMax, cell.getCol());
            yMin = Integer.min(yMin, cell.getRow());
            yMax = Integer.max(yMax, cell.getRow());
        }
        return new int[]{xMin, yMin, xMax, yMax};
    }

    @Override
    public int hashCode() {
        return this.toString().hashCode();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Block anotherBlock = (Block) o;

        return this.toString().equals(anotherBlock.toString());
    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        this.getCells().forEach(cell -> {
            stringBuilder.append(cell.toString()).append(",");
        });
        stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        return String.format("Block: [%s]", stringBuilder.toString());
    }

    public List<Cell> getCells() {
        return cells;
    }

    public char getCode() {
        return code;
    }
}
